//
//  ContactPersonDetailViewController.m
//  ERP
//
//  Created by goldeney on 15/1/21.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OAContactPersonDetailViewController.h"
#import "NSKeyedArchiverUserLogin.h"

#import "AddressBookEntity.h"
#import "NSDictionary+DataFormat.h"
#import "OAContactPersonDetailViewCell.h"

@interface OAContactPersonDetailViewController ()

@property (strong, nonatomic) NSDictionary *mDictionary;
@property (strong, nonatomic) AddressBookEntity *addressBookEntityodel;
@property (strong, nonatomic) NSArray *dataArray;

@end

@implementation OAContactPersonDetailViewController
@synthesize mDictionary = _mDictionary;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"联系人"];
    }
    return self;
}

//获取上一个页面传递的参数
- (void)getPassingParameter:(id)object
{
    if(!object) return;
    if ([object isKindOfClass:[AddressBookEntity class]]) {
        AddressBookEntity *addressBookEntityodel = object;
        self.addressBookEntityodel = addressBookEntityodel;
        
        self.contactsLable.text = addressBookEntityodel.userName.length >0 ? addressBookEntityodel.userName : @"未录入";
        self.positionLable.text = addressBookEntityodel.postName.length >0 ? addressBookEntityodel.postName : @"未录入";
        
        NSString *mobliePhoneLable = addressBookEntityodel.mobileNumber.length >0 ? addressBookEntityodel.mobileNumber : @"未录入";
        NSString *telPhoneLable = addressBookEntityodel.homePhone.length >0 ? addressBookEntityodel.homePhone : @"未录入";
        NSString *emailLable = addressBookEntityodel.companyEmail.length >0 ? addressBookEntityodel.companyEmail : @"未录入";
        NSString *companyLable = addressBookEntityodel.orgName.length >0 ? addressBookEntityodel.orgName : @"未录入";
        NSString *departmentLable = addressBookEntityodel.deptName.length >0 ? addressBookEntityodel.deptName : @"未录入";
        
        self.dataArray = @[@[@"ic_calllog_call_new",mobliePhoneLable,@"移动电话",@1],
                           @[@"ic_calllog_call_ip",telPhoneLable,@"固定电话",@0],
                           @[@"ic_combine_att_cloudmsg",emailLable,@"使用邮箱",@0],
                           @[@"ic_combine_att_contact",companyLable,@"所在公司",@0],
                           @[@"ic_combine_att_contact",departmentLable,@"所在部门",@0],];
        
    } else {
        NSDictionary *mDictionary = object;
        self.mDictionary = mDictionary;
        
        self.contactsLable.text = [mDictionary objectFormatStringForKey:@"userName" defaults:@"未录入"];
        self.positionLable.text = [mDictionary objectFormatStringForKey:@"postName" defaults:@"未录入"];
        
        NSString *mobliePhoneLable = [mDictionary objectFormatStringForKey:@"mobileNumber" defaults:@"未录入"];
        NSString *telPhoneLable = [mDictionary objectFormatStringForKey:@"tel" defaults:@"未录入"];
        NSString *emailLable = [mDictionary objectFormatStringForKey:@"companyEmail" defaults:@"未录入"];
        NSString *companyLable = [mDictionary objectFormatStringForKey:@"orgName" defaults:@"未录入"];
        NSString *departmentLable = [mDictionary objectFormatStringForKey:@"deptName" defaults:@"未录入"];
        
        self.dataArray = @[@[@"ic_calllog_call_new",mobliePhoneLable,@"移动电话",@1],
                           @[@"ic_calllog_call_ip",telPhoneLable,@"固定电话",@0],
                           @[@"ic_combine_att_cloudmsg",emailLable,@"使用邮箱",@0],
                           @[@"ic_combine_att_contact",companyLable,@"所在公司",@0],
                           @[@"ic_combine_att_contact",departmentLable,@"所在部门",@0],];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.tableHeaderView = self.tableHeaderView;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.iconImage.layer.cornerRadius = 4;
    self.iconImage.layer.masksToBounds = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- scroll delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset  = scrollView.contentOffset.y;
    
    if (yOffset < 0) {
        CGRect f = self.tableHeaderImage.frame;
        f.origin.y = yOffset;
        f.size.height =  -yOffset + self.tableHeaderView.bounds.size.height;
        self.tableHeaderImage.frame = f;
    }
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"OAContactPersonDetailViewCell";
    OAContactPersonDetailViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[OAContactPersonDetailViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSArray *dictionary = [self.dataArray objectAtIndex:indexPath.row];
    cell.iconImageView.image = [UIImage imageNamed:dictionary[0]];
    cell.infoLable.text = dictionary[1];
    cell.explainLable.text = dictionary[2];

    if ([dictionary[3] boolValue]) {
        cell.callButton.hidden = NO;
        cell.callButton.tag = indexPath.row;
        [cell.callButton addTarget:self action:@selector(sendMessageAction:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        cell.callButton.hidden = YES;
    }
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) [self callAction:indexPath];
    if (indexPath.row == 1) [self callAction2:indexPath];
}

#pragma mark -
#pragma mark MFMessageComposeViewControllerDelegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    //[controller dismissModalViewControllerAnimated:NO];//关键的一句   不能为YES
    [controller dismissViewControllerAnimated:NO completion:nil];
    switch ( result ) {
        case MessageComposeResultCancelled:
            [self alertWithTitle:@"温馨提示" msg:@"短信发送已取消"];
            break;
        case MessageComposeResultFailed:// send failed
            [self alertWithTitle:@"温馨提示" msg:@"短信发送成功"];
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"温馨提示" msg:@"短信发送失败"];
            break;
        default:
            break;
    }
}

- (void) alertWithTitle:(NSString *)title msg:(NSString *)msg {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self
                                          cancelButtonTitle:nil  otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)callAction:(NSIndexPath *)indexPath
{
    //获取电话号码
    NSMutableString *phoneNumber = [[NSMutableString alloc] init];
    [phoneNumber appendString:@"tel://"];
    
    NSString *mobliePhone = [_mDictionary objectFormatStringForKey:@"mobileNumber" defaults:nil];
    NSString *telPhone = [_mDictionary objectFormatStringForKey:@"homePhone" defaults:nil];
    if (mobliePhone && ![mobliePhone isEqualToString:@""] && indexPath.row == 0){//拨打移动号码
        [phoneNumber appendString:mobliePhone];
        
    } else if (telPhone && ![telPhone isEqualToString:@""] && indexPath.row == 1){//拨打固定号码
        [phoneNumber appendString:telPhone];
        
    } else {
        //未找到手机号码
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未找到联系人电话号码" delegate:self
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    //保存拨打联系人
    [self saveUserCallPhoneNumber:_mDictionary];
    
    //拨打电话(合法拨打电话方式)
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:phoneNumber];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

- (void)sendMessageAction:(id)sender
{
    NSString *mobliePhone = [_mDictionary objectFormatStringForKey:@"mobileNumber" defaults:@"未录入"];
    if (!mobliePhone || [mobliePhone isEqualToString:@""]){
        [self alertWithTitle:@"温馨提示" msg:@"未找到移动号码，无法发送短信"];
        return;
    }
    
    //发送短信前信息填充
    if( [MFMessageComposeViewController canSendText] ){
        UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
        
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc]init];
        controller.recipients = [NSArray arrayWithObject:mobliePhone];
        controller.body = [NSString stringWithFormat:@"现有紧急情况，请您看到短信后立即回复电话，谢谢！\n--%@ %@",
                           userInfo.CorpName, userInfo.username];
        controller.messageComposeDelegate = self;
        //[self presentModalViewController:controller animated:YES];
        [self presentViewController:controller animated:YES completion:nil];
        
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:@"来自汇基云"];//修改短信界面标题
    }else{
        [self alertWithTitle:@"温馨提示" msg:@"该设备没有短信功能"];
    }
}

#pragma mark
#pragma mark - 保存拨打联系人

- (void)saveUserCallPhoneNumber:(NSDictionary*)temp
{
    //保存拨打联系人
    NSString *phoneUserID = [[temp objectFormatStringForKey:@"userId"] MD5];
    NSArray *students = [AddressBookEntity MR_findByAttribute:@"identifyID" withValue:phoneUserID];
    if (students && students.count<=0){
        //插入联系人数据
        UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
        AddressBookEntity *person = [AddressBookEntity MR_createEntity];
        person.identifyID = phoneUserID;
        person.createUserId = [userInfo.Id MD5];
        person.userName = [temp objectFormatStringForKey:@"userName" defaults:@"未录入"];
        person.orgName = [temp objectFormatStringForKey:@"orgName" defaults:@"未录入"];
        person.deptName = [temp objectFormatStringForKey:@"deptName" defaults:@"未录入"];
        person.postName = [temp objectFormatStringForKey:@"postName" defaults:@"未录入"];
        person.officePhone = [temp objectFormatStringForKey:@"officePhone" defaults:@"未录入"];
        person.companyEmail = [temp objectFormatStringForKey:@"companyEmail" defaults:@"未录入"];
        person.homePhone = [temp objectFormatStringForKey:@"homePhone" defaults:@"未录入"];
        person.mobileNumber = [temp objectFormatStringForKey:@"mobileNumber" defaults:@"未录入"];
        person.callTime = [NSDate date];
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        
    } else {
        //更新联系人数据
        AddressBookEntity *entity = [students firstObject];
        entity.userName = [temp objectFormatStringForKey:@"userName" defaults:@"未录入"];
        entity.orgName = [temp objectFormatStringForKey:@"orgName" defaults:@"未录入"];
        entity.deptName = [temp objectFormatStringForKey:@"deptName" defaults:@"未录入"];
        entity.postName = [temp objectFormatStringForKey:@"postName" defaults:@"未录入"];
        entity.officePhone = [temp objectFormatStringForKey:@"officePhone" defaults:@"未录入"];
        entity.companyEmail = [temp objectFormatStringForKey:@"companyEmail" defaults:@"未录入"];
        entity.homePhone = [temp objectFormatStringForKey:@"homePhone" defaults:@"未录入"];
        entity.mobileNumber = [temp objectFormatStringForKey:@"mobileNumber" defaults:@"未录入"];
        entity.callTime = [NSDate date];
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    }
}


#pragma mark
#pragma mark - 更新拨打联系人

- (void)callAction2:(NSIndexPath *)indexPath
{
    //获取电话号码
    NSMutableString *phoneNumber = [[NSMutableString alloc] init];
    [phoneNumber appendString:@"tel://"];
    
    NSString *mobliePhone = self.addressBookEntityodel.mobileNumber;
    NSString *telPhone = self.addressBookEntityodel.homePhone;
    if (mobliePhone && ![mobliePhone isEqualToString:@""] && indexPath.row == 0){//拨打移动号码
        [phoneNumber appendString:mobliePhone];
        
    } else if (telPhone && ![telPhone isEqualToString:@""] && indexPath.row == 1){//拨打固定号码
        [phoneNumber appendString:telPhone];
        
    } else {
        //未找到手机号码
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未找到联系人电话号码" delegate:self
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    //更新联系人数据
    [self updateUserCallPhoneNumber:self.addressBookEntityodel];
    
    //拨打电话(合法拨打电话方式)
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:phoneNumber];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

- (void)updateUserCallPhoneNumber:(AddressBookEntity *)temp
{
    //更新联系人数据
    NSArray *students = [AddressBookEntity MR_findByAttribute:@"identifyID" withValue:temp.identifyID];
    AddressBookEntity *entity = [students firstObject];
    entity.callTime = [NSDate date];
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

@end
